//@ sourceURL=aa.js

/**
* 
* Created by chm on 2016/4/18.
 */

//添加jquery自定义验证，通过正则表达式验证密码
jQuery.validator.addMethod("passwordValidate",function(value,element){
	
	var regex = /^[0-9a-zA-Z_]{6,12}$/;
	return this.optional(element)||(regex.test(value));
		
	},"密码6-12位，由字母、数字或下划线组成，请重新输入！");
jQuery.validator.addMethod("emailValidate",function(value,element){
	
	var regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
	return this.optional(element)||(regex.test(value));
		
	},"邮箱格式错误，请重新输入！");




var loadDiv = null;
isUserNameValidator();
$(function () {
	loadDiv = $("#loadDiv").loading();//初始化提示操作执行中

	//初始化角色列表
//	initRoleList();
	//初始化部门列表
	initDepartmentList();
    initAddWindow();
});

/*function createEditWindow(id, label, formId, options){
	options = $.extend({
        width: 400,
        height: 300
    },options || {});
	//初始化添加窗口
    var addWindow = $("#" + id);
    addWindow.dialog({
        autoOpen: false,
        width: options.width,
        height: options.height,
        resizable: false,
        title: label,
        modal: true,
        buttons: {
            "保存": function () {
                $("#" + formId).submit();
            },
            "取消": function () {
                $(this).dialog("close");
            }
        },
        close: function(){
        	$(".jBox-wrapper").remove();
        }
    });
    return addWindow;
}*/

/**
 * 初始化角色列表
 */
//function initRoleList(){
//    if($("#role option").length == 0){
//        $.post(
//                getPath() + "base/role/tree",
//                function(data){
//                    var result = eval("(" + data + ")");
//                    if(result.isSuccess){
//                        var resultObject = result.resultObject;
//                        if(resultObject.length > 0){
//                            var areaHtml = "";
//                            for(var i=0; i < resultObject.length; i++){
//                                var item = resultObject[i];
//                                areaHtml += "<option value='" + item.id + "'>" + item.name + "</option>";
//                            }
//                            $("#role").html(areaHtml);
//                            $("#updateRole").html(areaHtml);
//                        }
//                    }else
//                        alert(result.resultObject);
//                }
//            );
//    }
//}

/**
 * 初始化部门列表
 */
function initDepartmentList(){
    if($("#department option").length == 0){
        $.post(
                getPath() + "org/department/tree",{pid:0},
                function(data){
                    var result = eval("(" + data + ")");
                    if(result.isSuccess){
                        var resultObject = result.resultObject;
                        if(resultObject.length > 0){
                            var areaHtml = "";
                            for(var i=0; i < resultObject.length; i++){
                                var item = resultObject[i];
                                areaHtml += "<option value='" + item.id + "'>" + item.name + "</option>";
                            }
                            $("#department").html(areaHtml);
                            $("#updateDepartment").html(areaHtml);
                        }                            
                    }else
                        alert(result.resultObject);
                }
            );
    }
}


/**
 * 初始化添加窗口
 */
function initAddWindow(){
    //声明消息提示
    var toolTips = new Object();

    //设置表单验证
    $("#addForm").validate({
    	rules:{
    		//jQuery远程后台验证用户名是否一致
        	userName:{
        		required:true,
        		userNameValidate:true,
        		remote:{
        			url: getPath() +  "base/user/validateUser",
        			type: "post",
        			data:{
        				newName:function(){
    					return $("#userName").val();
    					}
        			}
        		}
        	},
        	password:{
        		required:true,
        		passwordValidate:true
        	},
        	email:{
        		emailValidate:true
        	}
        },
        messages:{
        	userName: {
        		required:"请输入用户名！",
        		remote: "已存在此用户名，请重新输入！"
        	},
    		password:{
    			required:"请输入密码！"
        	}	
        },
        errorPlacement: function(eror,element){
            /*var toolTip = toolTips[element.attr("id")];
            if(!toolTip){
                toolTip =   element.jBox('Tooltip', {
                    id:element.attr("id") + "-error",
                    position: {
                        x: 'right',
                        y: 'center'
                    },
                    outside: 'x'
                });
                element.trigger("mouseenter");
                toolTips[element.attr("id")] = toolTip;
            } else{
                toolTip.attach();
                element.trigger("mouseenter");
            }
            toolTip.setContent(eror.text());
            element.addClass("error-border");*/	
        	 var toolTip = createTooltip(toolTips,element.attr("id"));
	            toolTip.setContent(eror.text());
	            toolTip.close();
	            element.addClass("error-border");
        },
        success:function(label){
            var elementId = label.attr("id").substring(0,label.attr("id").length - 6);
            var toolTip = toolTips[elementId];
            $("#" + elementId).removeClass("error-border");
            toolTip.close();
            toolTip.detach();
        },
        submitHandler:function(form){
        	loadDiv.showLoading();
            post(getPath() + "base/user/add",
                $("#addForm").serialize(),
                function(resultObject){
                var errors = resultObject.errors;
                //判断后台是否有返回错误消息
                if(errors && errors.length > 0){
                	loadDiv.hideLoading();
                    for(var i=0; i < errors.length; i++){
                        var error = errors[i];
                        var toolTip = createTooltip(toolTips,error.field);
                        toolTip.setContent(error.defaultMessage);
                        $("#" + error.field).addClass("error-border");
                    }
                }else{
                	loadDiv.hideLoading();
                    createWindow("添加成功",{url: getPath() + "base/user/list/1/"+ pageSize + '?' +
							($("#isFilter").val() == 1 ? ("?" + $("#searchForm").serialize()) : "")}).dialog("open");
                }
            },function(resultObject){
        		loadDiv.hideLoading();
        		createWindow(resultObject).dialog('open');
        	});
     
        }
    });
    //隐藏列表，显示添加
	$('#dialog').show();
	$('.grid-list').hide();

	//取消
	$('#cancleBtn').click(function(){
		$('#dialog').hide();
		$('.grid-list').show();
	});
}


//=================判断电话号码是否唯一========================
	$("#telephone").blur(function(){
		/*jQuery.validator.addMethod("isPhone", function(value,element) { 
			var mobile = /^1[34578]\d{9}$/; //手机号
			var tel = /^(\d{3,4}-)?\d{7,8}$/; //固话号
			return this.optional(element) || (mobile.test(value)) || (tel.test(value)); 
		}, "请正确填写号码"); */
		if(!(/^1[34578]\d{9}$/.test($("#telephone").val()))){
			document.getElementById("telephoneSpan").innerText = " 请填写正确的电话号码!";
		}else{
			$.ajax({
				type:"post",
				url:getPath() +  "base/user/validateTelephone",
				//contentType: "application/json; charset=utf-8",
				dataType: "json",//表示后台返回的数据是json对象
				data :{
					newTelephone:function(){
					return $("#telephone").val();}
				},
				success: function (data) {
					if(data==true){
						document.getElementById("telephoneSpan").innerText = "";
					}else if(data==false){
						document.getElementById("telephoneSpan").innerText = " 号码已存在!";
					}
				},
				error: function (error) {
					
				}
			});
		}
	});
	
	
